<template>
  <div class="pagination">
    <button :disabled="pageNo===1" @click.prevent="$emit('getPageNo',pageNo-1)">上一页</button>
    <button :class="{active:pageNo===1}" @click.prevent="$emit('getPageNo', 1)" v-if="startAndEndNum.start>1">1</button>
    <!-- 起始页大于2，即起始页从3开始，3、4、5、6、7，才需要 -->
    <button v-if="startAndEndNum.start>2">···</button>
    <template v-for="(page,index) in startAndEndNum.end">
      <button :class="{active:pageNo===page}" v-if="page>=startAndEndNum.start" :key="index" @click.prevent="$emit('getPageNo',page)">{{page}}</button>
    </template>
    <!-- 结束页小于最大页减1，即总共10页，结束页为9或者10都不需要 -->
    <button v-if="startAndEndNum.end<totalPage-1">···</button>
    <button :class="{active:pageNo===totalPage}" v-if="startAndEndNum.end<totalPage" @click.prevent="$emit('getPageNo',totalPage)">{{totalPage}}</button>
    <button :disabled="pageNo===totalPage" @click.prevent="$emit('getPageNo',pageNo+1)">下一页</button>
    
    <button style="margin-left: 30px">共 {{total}} 条</button>
  </div>
</template>

<script>
  export default {
    name: "Pagination",
    props: ['pageNo','pageSize','total','continues'],
    computed: {
      // 计算属性，算出总共有几页
      totalPage(){
        return Math.ceil(this.total / this.pageSize)
      },
      // 计算出连续页码的起始数字和结束数字
      startAndEndNum(){
        // 解构
        const {continues, totalPage, pageNo} = this
        let start = 0,end = 0
        // 先判断有没有特殊情况：连续页码数是5（代表页码至少5页），但如果总页码只有4页或以下，就不适用普通情况
        if (continues > totalPage) {
          // 连续页码大于总页码，不正常现象，起始页为1，结束页为总页
          start = 1
          end = totalPage
        }else{
          // 正常现象，连续页码是5，总页数大于5
          start = pageNo - Math.floor(continues/2)
          end = pageNo + Math.floor(continues/2)
          // 注意：如果此时当前页是1，起始页就变成了-1，结束页是3.分页器没有负数和0
          if (start < 1) {
            start = 1
            end = continues
          }
          if (end > totalPage) {
            // 如果当前页码是最后一页或倒数第二页，则要修改
            end = totalPage
            start = totalPage - continues + 1
          }
        }
        return {start,end}
      }
    },
    methods: {
    }
  }
</script>

<style lang="less" scoped>
  .pagination {
    text-align: center;
    button {
      margin: 0 5px;
      background-color: #f4f4f5;
      color: #606266;
      outline: none;
      border-radius: 2px;
      padding: 0 4px;
      vertical-align: top;
      display: inline-block;
      font-size: 13px;
      min-width: 35.5px;
      height: 28px;
      line-height: 28px;
      cursor: pointer;
      box-sizing: border-box;
      text-align: center;
      border: 0;

      &[disabled] {
        color: #c0c4cc;
        cursor: not-allowed;
      }

      &.active {
        cursor: not-allowed;
        background-color: #409eff;
        color: #fff;
      }
    }
  }
  .active{
    background-color: skyblue;
  }
</style>
